package com.sds.replicator.servlets;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: sdsbirdman
 * Date: 6/25/11
 * Time: 10:23 AM
 * To change this template use File | Settings | File Templates.
 */
@Deprecated
public abstract class ReplicatorServlet extends HttpServlet {

    private String defaultTarget;
    private Set<String> targetAddresses;
    private Logger logger = Logger.getLogger(getClass().getName());

    protected ReplicatorServlet(String defaultTarget, Set<String> targetAddresses) {
        this.defaultTarget = defaultTarget;
        this.targetAddresses = targetAddresses;
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String targetLocalPath = getTargetLocalPath(req);
        URL target = getTargetURL(targetLocalPath);
        URLConnection connection = target.openConnection();
        logger.info("fetching:" + target.toString());
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        fillHeaderProperties(httpURLConnection, req);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();
        IOUtils.copy(req.getInputStream(), connection.getOutputStream());
        int statusCode = httpURLConnection.getResponseCode();
        resp.setStatus(statusCode);

        for (Iterator i = httpURLConnection.getHeaderFields().entrySet().iterator(); i.hasNext(); ) {
            Map.Entry mapEntry = (Map.Entry) i.next();
            if (mapEntry.getKey() != null)
                resp.setHeader(mapEntry.getKey().toString(), ((List) mapEntry.getValue()).get(0).toString());
        }
        IOUtils.copy(connection.getInputStream(), resp.getOutputStream());
    }

    private URLConnection fillHeaderProperties(HttpURLConnection connection, HttpServletRequest req) throws ProtocolException {
        connection.setRequestMethod(req.getMethod());
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(true);
        Enumeration enumeration = req.getHeaderNames();

        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement().toString();
            if (!(name.equals("Host") || name.equals("Accept-Encoding"))) {
                connection.addRequestProperty(name, req.getHeader(name));
            }
        }
        return connection;
    }

    private URL getTargetURL(String targetLocalPath) throws MalformedURLException {
        if (targetLocalPath.length() == 1) {
            return new URL(defaultTarget);
        } else {
            return new URL(defaultTarget + targetLocalPath);
        }
    }

    private String getTargetLocalPath(HttpServletRequest req) {
        if (!StringUtils.isBlank(req.getQueryString())) {
            return req.getPathInfo() + "?" + req.getQueryString();
        } else {
            return req.getPathInfo();
        }
    }
}
